package com.innovation.ic.im.end.data.controller;

import com.alibaba.fastjson.JSON;
import com.innovation.ic.im.end.base.model.im_erp9.Client;
import com.innovation.ic.im.end.base.pojo.ApiResult;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.RedisStorage;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;

/**
 * 客户端信息API
 */
@RestController
@RequestMapping("/api/v2/client")
@DefaultProperties(defaultFallback = "defaultFallback")
public class ClientController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(ClientController.class);

    /**
     * 删除redis中CLIENT:开头的数据，将client表中的数据导入redis
     * @return
     */
    @HystrixCommand
    @RequestMapping(value = "/importClientIntoRedis", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> importClientIntoRedis(HttpServletRequest request, HttpServletResponse response) {
        log.info("删除redis中CLIENT:开头的数据，将client表中的数据导入redis");

        // 删除redis中CLIENT:开头的数据
        Set<String> keySet = redisManager.keysPrefix(RedisStorage.CLIENT);
        redisManager.del(keySet);
        // 将client表中的数据导入redis
        ServiceResult<List<Client>> serviceResult = clientService.findAll();
        if (null != serviceResult && null != serviceResult.getResult()) {
            List<Client> clientList = serviceResult.getResult();
            for (int i = 0; i < clientList.size(); i++) {
                Client client = clientList.get(i);
                redisManager.sAdd(RedisStorage.CLIENT, JSON.toJSONString(client));
                //redisManager.expire(RedisStorage.CLIENT, redisParamConfig.getTimeout());
            }
        }

        ApiResult<Boolean> apiResult = new ApiResult<Boolean>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.INSERT_SUCCESS);
        return new ResponseEntity<ApiResult>(apiResult, HttpStatus.OK);
    }
}